package com.woniuxy.commons.interceptor;


import java.lang.reflect.Method;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.woniuxy.commons.anno.HasRole;
import com.woniuxy.commons.dto.AuthDto;
import com.woniuxy.commons.service.RemoteAuthService;

/**
 * @author： 雷鹏
 * Date: 2020/7/22 0:03
 */
@Component
public class AuthInterceptor extends HandlerInterceptorAdapter {

    @Autowired
    private RemoteAuthService remoteAuthService;

    // preHandle 方法执行前
    // 返回true，表示放行，去执行方法
    // 返回false，表示拦截，不继续执行将要执行的方法
    // handler:指向将要执行的方法、获取资源
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {

        // refreshToken
        String refreshToken = request.getHeader("refreshToken");

        System.out.println("lanjie-------------");
        // 获取角色、权限信息
        if (handler instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;

            // 获取将要执行的方法
            Method method = handlerMethod.getMethod();
            // 判断方法上是否有相关的注解
            if (method.isAnnotationPresent(HasRole.class)) {

                System.out.println("lanjie222-------------");
                // 如果有则获取注解的值
                HasRole hasRole = method.getAnnotation(HasRole.class);// 获取注解对象
                // 获取值
                String role = hasRole.value();
                if (role != null && role.length() != 0) {

                    // 通过feign调用auth模块校验角色的方法，获取结果

                    System.out.println("lanjie333-------------");
                    if (!remoteAuthService.hasRole(refreshToken, role)) {
                        System.out.println("lanjie44444-------------");
                        AuthDto authDto = new AuthDto().setCode(500).setMessage("你没有权限");
                        response.setContentType("application/json;charset=utf-8");
                        response.getWriter().write(new ObjectMapper().writeValueAsString(authDto));
                        return false;
                    } else {
                        return true;
                    }

                }

            }

        }

        return super.preHandle(request, response, handler);

    }

}
